import { useState, useEffect } from "react";

// 接口定义一个省份的数据格式
interface IProvince {
  id: string;
  name: string;
}

// 接口定义一个城市的数据格式
interface ICity {
  id: string;
  provinceId: string;
  name: string;
}

export default function App() {
  // 省份列表数据
  const [provinceList, setProvinceList] = useState<IProvince[]>([]);
  // 城市列表数据
  const [cityList, setCityList] = useState<ICity[]>([]);
  // 当前选择的省份Id
  const [curProvinceId, setCurProvinceId] = useState("");
  // 当前选择的城市Id
  const [curCityId, setCurCityId] = useState("");

  // 获取省份列表数据的方法
  const getProvinceList = () => {
    // 调用接口
    fetch("http://localhost:3000/province")
      .then((response) => response.json())
      .then((response) => {
        // 将 response 赋值给 provinceList
        setProvinceList(response);
      });
  };

  const getCityList = () => {
    // 将 curCityId 重置一下
    setCurCityId("");

    // 调用接口
    fetch(`http://localhost:3000/city?provinceId=${curProvinceId}`)
      .then((response) => response.json())
      .then((response) => {
        console.log("response", response);
        // 将 reponse 赋值给 cityList
        setCityList(response);
      });
  };

  useEffect(() => {
    // 挂载完成，默认调用一下省份数据
    getProvinceList();
  }, []);

  useEffect(() => {
    if (!curProvinceId) return;
    console.log("curProvinceId 有变化");
    // 调用 getCityList 方法
    getCityList();
  }, [curProvinceId]);

  return (
    <div>
      <h1>App</h1>
      <hr />

      <label>省份：</label>
      <select
        value={curProvinceId}
        onChange={(event) => setCurProvinceId(event.target.value)}
      >
        <option value="" disabled>
          请选择
        </option>
        {provinceList.map((item) => (
          <option key={item.id} value={item.id}>
            {item.name}
          </option>
        ))}
      </select>

      <label>城市：</label>
      <select
        value={curCityId}
        onChange={(event) => setCurCityId(event.target.value)}
      >
        <option value="" disabled>
          请选择
        </option>
        {cityList.map((item) => (
          <option key={item.id} value={item.id}>
            {item.name}
          </option>
        ))}
      </select>

      <button>点击，输出当前的 省市</button>
    </div>
  );
}
